import { ScrollView, View, Text, Textarea, Picker, Image, Input } from '@tarojs/components';
import React, { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { connect } from 'react-redux';
import './index.less';
import * as T from './types';
import actions from './actions';
import { store2Props } from './selectors';
import youImg from '@/assets/image/my/you.png';
import ChooseImageView from '@/pages/common/image-upload/choose-image-view';
import api from 'api';

const flowState = (name) => {
  if (name == '电路故障') {
    //电路故障
    return 1;
  } else if (name == '自来水管故障') {
    //自来水管故障
    return 2;
  } else if (name == '供暖设备故障') {
    //供暖设备故障
    return 3;
  } else if (name == '家电维修') {
    //家电维修
    return 4;
  } else if (name == '其他') {
    //其他
    return 99;
  }
};

actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class Index extends Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      text: '',
      imgList: [],
      typeList: ['电路故障', '自来水管故障', '供暖设备故障', '家电维修', '其他'],
      type: '',
      phone: '',
    };
  }

  componentDidMount() { }

  componentDidShow() { }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  onDetailFileChange = (detailFiles) => {
    this.setState(
      {
        detailFiles,
      },
      () => {
        let imgList = [];
        detailFiles.map((item) => {
          imgList.push(item.url);
        });
        this.setState({ imgList });
        console.log(this.state.detailFiles);
      },
    );
  };

  async repairAdd() {
    const { imgList, type, text, phone } = this.state;
    let refImage = [];
    let userInfo = Taro.getStorageSync('b2b-wechat@login').user;
    if (text.trim() == '') {
      Taro.showToast({
        title: '请填写报修详情！',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    if (imgList.length == 0) {
      Taro.showToast({
        title: '报修图片不能为空！',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    if (type == '') {
      Taro.showToast({
        title: '请选择报修类型！',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    if (phone.trim() == '') {
      Taro.showToast({
        title: '请填写联系方式！',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    const reg = /^1[3456789]\d{9}$/;
    if (!reg.test(phone)) {
      Taro.showToast({
        title: '请输入正确的手机号！',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    Taro.showLoading({
      title: '提交中...',
    });
    imgList.map((item) => {
      refImage.push({ type: '4', imageUrl: item });
    });
    let params = {
      userId: userInfo.id,
      reporter: userInfo.name,
      phone: userInfo.phone,
      communityCode: userInfo.communityCode,
      communityId: userInfo.communityId,
      type: flowState(type),
      description: text,
      alternatePhone: phone,
      refImage,
    };
    console.log(params);
    let res = await api.repairController.repairAdd(params);
    Taro.hideLoading();
    if (res.success) {
      Taro.showToast({
        title: '新增成功！',
        icon: 'none',
        duration: 2000,
      });
      Taro.navigateBack();
    }
  }

  render() {
    let { text, imgList, typeList, type } = this.state;
    let detailImages = [];
    imgList.map((item) => {
      detailImages.push({ url: item });
    });
    return (
      <ScrollView className="packageAAddRepair" scrollY>
        <View className="form">
          <Textarea
            placeholderStyle="color:#BFBFBF;"
            className="textarea"
            autoHeight
            maxlength={256}
            placeholder="请输入问题详情，以便我们更好的处理。"
            value={text ? text.substring(0, 256) : ''}
            onInput={(e) => {
              let sss = text;
              sss = e.detail.value;
              if (sss.length >= 256) {
                sss = sss.substring(0, 256);
                Taro.showToast({
                  title: '字数已达上限',
                  icon: 'none',
                  duration: 2000,
                });
              }
              this.setState({
                text: sss,
              });
            }}
          />
        </View>
        <View className="length">{text.length}/256</View>
        <ChooseImageView files={detailImages} maxCount="3" onFileChange={this.onDetailFileChange.bind(this)} />
        <View className="from-select t_title">
          <Text className="select-label">报修类型</Text>
          <Picker
            mode="selector"
            range={typeList}
            onChange={(e) => {
              this.setState({
                type: typeList[e.detail.value],
              });
            }}
            style={{ flex: 1 }}
          >
            <View className="row">
              <Text className="t_right">{type ? type : '请选择类型'}</Text>
              <Image className="youImg" src={youImg} mode="widthFix" />
            </View>
          </Picker>
        </View>
        <View className="from-select t_title">
          <Text className="select-label">联系方式</Text>
          <View className="row">
            <Input
              className="mess-text"
              maxlength={11}
              type="number"
              placeholder="请输入您的手机号"
              placeholder-style="color:#999999;"
              onInput={(e) => {
                this.setState({ phone: e.detail.value });
              }}
            />
          </View>
        </View>
        <View className="bottom">
          <View className="btn_box">
            <Text
              className="btn-release"
              onClick={() => {
                this.repairAdd();
              }}
            >
              发布
            </Text>
          </View>
        </View>
      </ScrollView>
    );
  }
}
